﻿using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace YDT_ConfigCentor.ConfigCentors
{
    /// <summary>
    /// 事件总线模块封装
    /// </summary>
    public static class CapDistributedEventBusWebApplicationBuilderExtenions
    {
        public static WebApplicationBuilder AddDistributedEventBus<T>(this WebApplicationBuilder builder) 
            where T:DbContext
        {
           var Configuration = builder.Configuration;
            // 3、集成DotNetCore.CAP
            builder.Services.AddCap(options => {
                // 3.1、集成rabbitmq(事件接收器)
                options.UseRabbitMQ(rb => {
                    rb.HostName = Configuration["DistributedEventBus:Cap:RabbitMQ:HostName"];
                    rb.UserName = Configuration["DistributedEventBus:Cap:RabbitMQ:UserName"];
                    rb.Password = Configuration["DistributedEventBus:Cap:RabbitMQ:Password"];
                    rb.Port = int.Parse(Configuration["DistributedEventBus:Cap:RabbitMQ:Port"]);
                    // rb.VirtualHost = "/productservice"; //虚拟主机 
                    rb.VirtualHost = Configuration["DistributedEventBus:Cap:RabbitMQ:VirtualHost"]; //虚拟主机 
                });

                // 3.2、集成缓存（事件存储器）
                //options.UseInMemoryStorage();

                // 3.3、集成控制面板
                options.UseDashboard();

                // 3.4、事件失败重试次数
                options.FailedRetryCount = int.Parse(Configuration["DistributedEventBus:Cap:FailedRetryCount"]);// 失败重试次数
                options.FailedRetryInterval = int.Parse(Configuration["DistributedEventBus:Cap:FailedRetryInterval"]); //每3s重试一次

                // 3.5、集成MySQL
                options.UseMySql(Configuration["DistributedEventBus:Cap:MySql:Address"]);
                options.UseEntityFramework<T>();

            });
            return builder;
        }
    }
}
